package com.zbkj.service.service.water.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.model.water.RzDevice;
import com.zbkj.common.request.water.RzDeviceSaveRequest;
import com.zbkj.common.request.water.RzDeviceSearchRequest;
import com.zbkj.service.dao.water.RzDeviceDao;
import com.zbkj.service.service.water.RzDeviceService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import cn.hutool.core.util.ObjectUtil;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.result.CommonResultCode;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RzDeviceServiceImpl extends ServiceImpl<RzDeviceDao, RzDevice> implements RzDeviceService {

    @Resource
    private RzDeviceDao rzDeviceDao;

    @Override
    public PageInfo<RzDevice> getPage(RzDeviceSearchRequest request) {
        PageHelper.startPage(request.getPage(), request.getLimit());
        List<RzDevice> list = rzDeviceDao.selectPageList(request);
        return new PageInfo<>(list);
    }

    @Override
    public Boolean add(RzDeviceSaveRequest request) {
        RzDevice device = new RzDevice();
        BeanUtils.copyProperties(request, device);
        device.setId(null);
        return save(device);
    }

    @Override
    public Boolean updateDevice(RzDeviceSaveRequest request) {
        RzDevice device = getById(request.getId());
        if (ObjectUtil.isEmpty(device)) {
            throw new CrmebException(CommonResultCode.NOT_FOUND, "设备不存在");
        }
        if (Boolean.TRUE.equals(device.getIsOnline())) {
            throw new CrmebException(CommonResultCode.VALIDATE_FAILED, "设备运行中，禁止修改");
        }
        BeanUtils.copyProperties(request, device);
        return updateById(device);
    }

    @Override
    public Boolean deleteById(Integer id) {
        RzDevice device = getById(id);
        if (ObjectUtil.isEmpty(device)) {
            throw new CrmebException(CommonResultCode.NOT_FOUND, "设备不存在");
        }
        if (Boolean.TRUE.equals(device.getIsOnline())) {
            throw new CrmebException(CommonResultCode.VALIDATE_FAILED, "设备运行中，禁止删除");
        }
        return removeById(id);
    }

    @Override
    public Boolean updateOnline(Integer id, Boolean online) {
        RzDevice device = getById(id);
        if (ObjectUtil.isEmpty(device)) {
            throw new CrmebException(CommonResultCode.NOT_FOUND, "设备不存在");
        }
        device.setIsOnline(online);
        return updateById(device);
    }
}
